home *** CD-ROM | disk | FTP | other *** search
- Path: topaz.cqu.edu.au!naderr
- From: naderr@topaz.cqu.edu.au
- Newsgroups: comp.lang.c++
- Subject: handling void
- Date: 30 Mar 96 07:31:51 +1000
- Organization: Central Queensland University, Australia
- Message-ID: <1996Mar30.073151@topaz>
- NNTP-Posting-Host: topaz.cqu.edu.au
-
- Hi,
-
- In a header file I have a class foo which has
- a public data member a pointer to a structure like ...
-
- typedef class node_tag {
- public:
- void *data;
- node_tag *next;
- node(){};
- }node;
-
- class foo {
- //private: let it be public as we want to test whats in it!
- public:
- node *head;
-
- public:
- foo(void); // constructor
- ~foo(void); // destructor
- void func(void *object, int object_size);
- }
-
-
- and in its .C file I have
-
- void foo::func(void *object, int object_size)
- {
- node *new_node;
- node *ptr;
-
- // create new_node
- new_node = new node();
- // allocate memory for object
- if (NULL == (new_node->data = malloc(object_size))){
- perror("malloc");
- exit (EXIT_FAILURE);
- }
- // copy contents of object into data
- if (NULL == memcpy(new_node->data,object,object_size)){
- perror("memcpy");
- exit (EXIT_FAILURE);
- }
-
- // If this is the first node ...
- if (head == NULL)
- if (NULL == (head = new node())){
- perror("new");
- exit (EXIT_FAILURE);
- }
-
- ptr = head;
- while (ptr->next != NULL)
- // warning: ANSI C++ forbids implicit conversion
- // from `void *' in assignment.
- // But it compiles fine.
- ptr = (void*)(ptr->next);
-
- // append object
- ptr->next = new_node;
- }
-
-
- Then in a another .C file that I'm using to test the stuff above I have ...
-
-
- typedef struct data_struct_tag{
- int i;
- char str[20];
- }data_struct;
-
-
- Now, some declarations
-
- data_struct *t, *test_ptr;
- foo *f;
-
- and allocate some memory storage for them ...
-
- f = new foo();
-
- if (NULL == (t = (data_struct*)malloc(sizeof(data_struct)))){
- perror ("whatever");
- exit (1);
- }
-
- Now assign t some values ...
-
- t->i = 256;
- strcpy(t->str,"this is a test");
-
- have peek at what it's got ...
-
- cout << t->str << " " << t->i "\n";
-
- and yes it holds the assigned values.
-
- But .....
-
- when I do:
-
- f->func(t,sizeof(data_struct));
-
- ptr = (data_struct*)(f->head->data);
-
- cout << ptr->str << "" << ptr->i << "\n";
-
- I get goobly-gook nothing like "this is a test 256".
-
- when I run the debuger (gdb ... via xxgdb) and peek at
-
- func(t,sizeof(data_struct));
-
- i.e. when it is just entered into the first statement of
-
- void foo::func(void *object, int object_size)
-
- I typecast object (which is void) to (data_struct*)object and have a peek
- at (data_struct*)object->str and (data_struct*)object->i and they
- have goobly-gook instead of the values that I asigned 't'.
-
- Any one know what's going on? what point am I missing?
-
- Any ideas greatly appreciated ... if you are going to "reply" please email
- me as well as "followup".
-
- TIA
-
- Rob
-
-
-
-
-